import { WebSocketServer } from 'ws';
import jwt from 'jsonwebtoken';
import db from '../config/db.js';

const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';

class CustomerServiceWebSocket {
  constructor(server) {
    this.wss = new WebSocketServer({ 
      server, 
      path: '/ws/customer-service' 
    });
    this.clients = new Map(); // 存储客户端连接
    this.serviceAgents = new Map(); // 存储客服代理连接
    this.userSessions = new Map(); // 存储用户会话
    
    this.setupWebSocket();
  }

  setupWebSocket() {
    this.wss.on('connection', (ws, req) => {
      console.log('新的WebSocket连接建立');
      
      ws.on('message', async (message) => {
        try {
          const data = JSON.parse(message);
          await this.handleMessage(ws, data);
        } catch (error) {
          console.error('处理WebSocket消息失败:', error);
          ws.send(JSON.stringify({
            type: 'error',
            message: '消息格式错误'
          }));
        }
      });

      ws.on('close', () => {
        this.handleDisconnection(ws);
      });

      ws.on('error', (error) => {
        console.error('WebSocket错误:', error);
        this.handleDisconnection(ws);
      });
    });
  }

  async handleMessage(ws, data) {
    switch (data.type) {
      case 'auth':
        await this.handleAuth(ws, data);
        break;
      case 'message':
        await this.handleUserMessage(ws, data);
        break;
      case 'service_auth':
        await this.handleServiceAuth(ws, data);
        break;
      case 'service_message':
        await this.handleServiceMessage(ws, data);
        break;
      default:
        ws.send(JSON.stringify({
          type: 'error',
          message: '未知消息类型'
        }));
    }
  }

  async handleAuth(ws, data) {
    try {
      // 验证用户token
      const decoded = jwt.verify(data.token, JWT_SECRET);
      
      if (decoded.type !== 'access') {
        ws.send(JSON.stringify({
          type: 'error',
          message: '无效的token类型'
        }));
        return;
      }

      // 获取用户信息
      const userInfo = await this.getUserInfo(decoded.phone);
      if (!userInfo) {
        ws.send(JSON.stringify({
          type: 'error',
          message: '用户不存在'
        }));
        return;
      }

      // 存储用户连接
      this.clients.set(ws, {
        type: 'user',
        userId: userInfo.id,
        phone: decoded.phone,
        userInfo: userInfo
      });

      // 创建或获取用户会话
      let session = this.userSessions.get(decoded.phone);
      if (!session) {
        session = {
          userId: userInfo.id,
          phone: decoded.phone,
          userInfo: userInfo,
          messages: [],
          status: 'waiting', // waiting, chatting, closed
          assignedAgent: null,
          createdAt: new Date()
        };
        this.userSessions.set(decoded.phone, session);
      }

      ws.send(JSON.stringify({
        type: 'auth_success',
        userInfo: userInfo,
        session: session
      }));

      console.log(`用户 ${userInfo.username} 已连接客服系统`);

    } catch (error) {
      console.error('用户认证失败:', error);
      ws.send(JSON.stringify({
        type: 'error',
        message: '认证失败'
      }));
    }
  }

  async handleServiceAuth(ws, data) {
    try {
      // 验证客服token（这里可以有不同的验证逻辑）
      const decoded = jwt.verify(data.token, JWT_SECRET);
      
      // 存储客服连接
      this.serviceAgents.set(ws, {
        type: 'service',
        agentId: decoded.agentId || 'agent_001',
        agentName: decoded.agentName || '客服小助手'
      });

      ws.send(JSON.stringify({
        type: 'service_auth_success',
        message: '客服认证成功'
      }));

      console.log('客服代理已连接');

    } catch (error) {
      console.error('客服认证失败:', error);
      ws.send(JSON.stringify({
        type: 'error',
        message: '客服认证失败'
      }));
    }
  }

  async handleUserMessage(ws, data) {
    const clientInfo = this.clients.get(ws);
    if (!clientInfo || clientInfo.type !== 'user') {
      ws.send(JSON.stringify({
        type: 'error',
        message: '未认证的用户'
      }));
      return;
    }

    const session = this.userSessions.get(clientInfo.phone);
    if (!session) {
      ws.send(JSON.stringify({
        type: 'error',
        message: '会话不存在'
      }));
      return;
    }

    // 创建消息对象
    const message = {
      id: Date.now().toString(),
      content: data.content,
      sender: 'user',
      timestamp: new Date().toISOString(),
      type: data.messageType || 'text'
    };

    // 保存消息到会话
    session.messages.push(message);

    // 发送消息给用户确认
    ws.send(JSON.stringify({
      type: 'message',
      message: message
    }));

    // 如果有分配的客服，转发消息给客服
    if (session.assignedAgent) {
      const agentWs = this.findAgentConnection(session.assignedAgent);
      if (agentWs) {
        agentWs.send(JSON.stringify({
          type: 'user_message',
          session: session,
          message: message
        }));
      }
    } else {
      // 如果没有分配的客服，分配给第一个可用的客服
      this.assignAgentToSession(session);
    }

    // 保存消息到数据库
    await this.saveMessageToDatabase(session.userId, message);
  }

  async handleServiceMessage(ws, data) {
    const agentInfo = this.serviceAgents.get(ws);
    if (!agentInfo || agentInfo.type !== 'service') {
      ws.send(JSON.stringify({
        type: 'error',
        message: '未认证的客服'
      }));
      return;
    }

    // 查找对应的用户会话
    const session = this.findSessionByAgent(agentInfo.agentId);
    if (!session) {
      ws.send(JSON.stringify({
        type: 'error',
        message: '没有找到对应的用户会话'
      }));
      return;
    }

    // 创建消息对象
    const message = {
      id: Date.now().toString(),
      content: data.content,
      sender: 'service',
      timestamp: new Date().toISOString(),
      type: data.messageType || 'text',
      agentId: agentInfo.agentId,
      agentName: agentInfo.agentName
    };

    // 保存消息到会话
    session.messages.push(message);

    // 发送消息给客服确认
    ws.send(JSON.stringify({
      type: 'message',
      message: message
    }));

    // 发送消息给用户
    const userWs = this.findUserConnection(session.phone);
    if (userWs) {
      userWs.send(JSON.stringify({
        type: 'message',
        message: message
      }));
    }

    // 保存消息到数据库
    await this.saveMessageToDatabase(session.userId, message);
  }

  assignAgentToSession(session) {
    // 找到第一个可用的客服
    const availableAgent = Array.from(this.serviceAgents.values())[0];
    if (availableAgent) {
      session.assignedAgent = availableAgent.agentId;
      session.status = 'chatting';
      
      // 通知客服有新的用户会话
      const agentWs = this.findAgentConnection(availableAgent.agentId);
      if (agentWs) {
        agentWs.send(JSON.stringify({
          type: 'new_session',
          session: session
        }));
      }
    }
  }

  findAgentConnection(agentId) {
    for (const [ws, info] of this.serviceAgents) {
      if (info.agentId === agentId) {
        return ws;
      }
    }
    return null;
  }

  findUserConnection(phone) {
    for (const [ws, info] of this.clients) {
      if (info.type === 'user' && info.phone === phone) {
        return ws;
      }
    }
    return null;
  }

  findSessionByAgent(agentId) {
    for (const [phone, session] of this.userSessions) {
      if (session.assignedAgent === agentId) {
        return session;
      }
    }
    return null;
  }

  async getUserInfo(phone) {
    try {
      const result = await db.pool.promise().execute(
        'SELECT id, phone, username, img FROM user WHERE phone = ?',
        [phone]
      );
      
      const rows = result[0];
      if (rows.length > 0) {
        const user = rows[0];
        return {
          id: user.id,
          phone: user.phone,
          username: user.username,
          avatar: user.img || '/image/nv1.jpg'
        };
      }
      return null;
    } catch (error) {
      console.error('获取用户信息失败:', error);
      return null;
    }
  }

  async saveMessageToDatabase(userId, message) {
    try {
      await db.pool.promise().execute(
        'INSERT INTO customer_service_messages (user_id, content, sender, message_type, created_at) VALUES (?, ?, ?, ?, ?)',
        [userId, message.content, message.sender, message.type, message.timestamp]
      );
    } catch (error) {
      console.error('保存消息到数据库失败:', error);
    }
  }

  handleDisconnection(ws) {
    const clientInfo = this.clients.get(ws);
    const agentInfo = this.serviceAgents.get(ws);

    if (clientInfo) {
      console.log(`用户 ${clientInfo.userInfo?.username} 断开连接`);
      this.clients.delete(ws);
      
      // 更新会话状态
      const session = this.userSessions.get(clientInfo.phone);
      if (session) {
        session.status = 'closed';
      }
    }

    if (agentInfo) {
      console.log(`客服 ${agentInfo.agentName} 断开连接`);
      this.serviceAgents.delete(ws);
    }
  }
}

export default CustomerServiceWebSocket;
